package com.zx.sa.controller;

import java.util.HashMap;
import java.util.Map;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import reactor.core.publisher.Flux;

@Controller
@CrossOrigin(origins = "*")
@RequestMapping("/stream")
public class ChatStreamController {

    private final ChatClient chatClient;

    @Autowired
    public ChatStreamController(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    @RequestMapping("/index1")
    public String index(Model model) {
        return "stream1";
    }

    @RequestMapping("/index2")
    public String index2(Model model) {
        return "stream2";
    }

    /**
     * 文本流
     */
    @GetMapping(value = "/chat1", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public Flux<Map<String, Object>> chatStream(@RequestParam(value = "msg", defaultValue = "") String msg) {
        Flux<String> content = chatClient.prompt().user(msg).stream().content();
        return content.map(this::createResponse);
    }

    @GetMapping(value = "/chat2", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    @ResponseBody
    public Flux<String> chatStream2(@RequestParam(value = "msg", defaultValue = "") String msg) {
        return chatClient.prompt().user(msg).stream().content();
    }

    /**
     * 辅助方法用于构建 JSON 响应
     */
    private Map<String, Object> createResponse(String content) {
        Map<String, Object> response = new HashMap<>();
        response.put("content", content);
        return response;
    }

} 